package by.twouexplorer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.content.res.Resources;
import android.os.AsyncTask;

public final class Copier extends AsyncTask<Void, String, Boolean> {
    
    protected final Resources mResources;
    
    private Boolean mResult;
    private String mProgressMessage;
    private IProgressTracker mProgressTracker;
    private File source;
    private File destination;
    private int filesNumber;
    private int currentNumber;

    /* UI Thread */
    public Copier(Resources resources, String src, String dst) {
    	// Keep reference to resources
    	mResources = resources;
    	// Initialise initial pre-execute message
    	mProgressMessage = "Starting";
    	source = new File(src);
    	destination = new File (dst);
    }

    /* UI Thread */
    public void setProgressTracker(IProgressTracker progressTracker) {
    	// Attach to progress tracker
    	mProgressTracker = progressTracker;
    	// Initialise progress tracker with current Copier state
    	if (mProgressTracker != null) {
    		mProgressTracker.onProgress(mProgressMessage);
    		if (mResult != null) {
    			mProgressTracker.onComplete();
    		}
    	}	
    }

    /* UI Thread */
    @Override
    protected void onCancelled() {
    	// Detach from progress tracker
    	mProgressTracker = null;
    }
    
    /* UI Thread */
    @Override
    protected void onProgressUpdate(String... values) {
    	// Update progress message 
    	mProgressMessage = values[0];
    	// And send it to progress tracker
    	if (mProgressTracker != null) {
    		mProgressTracker.onProgress(mProgressMessage);
    	}
    }

    /* UI Thread */
    @Override
    protected void onPostExecute(Boolean result) {
    	// Update result
    	mResult = result;
    	// And send it to progress tracker
    	if (mProgressTracker != null) {
    		mProgressTracker.onComplete();
    	}
    	// Detach from progress tracker
    	mProgressTracker = null;
    }

    /* Separate Thread */
    @Override
    protected Boolean doInBackground(Void... arg0) {
    	// Working in separate thread
	    // Check if Copier is cancelled
    	if (isCancelled()) {
    		// This return causes onPostExecute call on UI thread
    		return false;
    	}
    	if(copy(source, destination)) return true;
    	else return false;
	   	// This return causes onPostExecute call on UI thread
    }
    
    protected boolean copy(File sourceFile, File destinationFile){
    	if (sourceFile.isDirectory()){
			 if (!destinationFile.exists()){
				 destinationFile.mkdir();
			 }
			 String files[] = sourceFile.list();
			 filesNumber=files.length;
			 currentNumber=0;
			 for(int i = 0; i < files.length; i++)
				 copy(new File(sourceFile.getAbsoluteFile() + "/" + files[i]), new File(destinationFile.getAbsolutePath() + "/" + files[i]));
		}
    	else{
    		try{
    			if(filesNumber==0) filesNumber=1; //Only one file copy
    			currentNumber++;
    			publishProgress("Copy "+currentNumber+" of "+filesNumber);
    			if(!destinationFile.exists()) destinationFile.createNewFile();
    			FileInputStream fis = new FileInputStream(sourceFile); 
    			FileOutputStream fos = new FileOutputStream(destinationFile); 
    			FileChannel fcin = fis.getChannel(); 
    			FileChannel fcout = fos.getChannel();
    			fcin.transferTo(0, fcin.size(), fcout);
    			fcin.close();
        		fcout.close();
        		fis.close();
        		fos.close();
    		}catch(FileNotFoundException e){
    			e.printStackTrace();
    			return false;
    		}catch(IOException e){
    			e.printStackTrace();
    			return false;
    		}
    	}
    	return true;
    	
    }
}
